package com.supply.service.impl;

import com.supply.mapper.DepartmentMapper;
import com.supply.mapper.UserMapper;
import com.supply.pojo.Department;
import com.supply.pojo.DepartmentExample;
import com.supply.pojo.User;
import com.supply.pojo.UserExample;
import com.supply.req.DepartmentReq;
import com.supply.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class DepartmentServiceImpl implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Department> queryByCondition(DepartmentReq departmentReq) {
        DepartmentExample example = new DepartmentExample();
        DepartmentExample.Criteria criteria = example.createCriteria();
        if (departmentReq != null){
            if (!ObjectUtils.isEmpty(departmentReq.getName())){
                criteria.andNameLike("%" + departmentReq.getName() + "%");
            }
            if (!ObjectUtils.isEmpty(departmentReq.getRemark())){
                criteria.andRemarkLike("%" + departmentReq.getRemark() + "%");
            }
        }
        return departmentMapper.selectByExample(example);
    }

    @Override
    public int saveOrUpdate(Department department) {
        List<Department> departments = departmentMapper.selectByExample(null);
        if (department.getId() == null){
            for (Department dept : departments) {
                if (dept.getName().equals(department.getName())){
                    return 0;
                }
            }
            return departmentMapper.insert(department);
        }else {
            for (Department dept : departments) {
                if (dept.getName().equals(department.getName()) && (dept.getId() != department.getId())){
                    return 0;
                }
            }
            return departmentMapper.updateByPrimaryKey(department);
        }
    }

    @Override
    public int deleteById(Long id) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andDeptIdEqualTo(id);
        List<User> users = userMapper.selectByExample(userExample);
        if (!users.isEmpty()){
            return 0;
        }
        return departmentMapper.deleteByPrimaryKey(id);
    }
}
